//
//  Helper.m
//  JiPei
//
//  Created by hh on 16/1/29.
//  Copyright © 2016年 hh. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "Helper.h"
#import "LoginViewController.h"
#import <CommonCrypto/CommonDigest.h>
#include <ifaddrs.h>
#include <arpa/inet.h>

CGRect CGRectInsetMy(CGRect rect, CGFloat dx, CGFloat dy){
    return CGRectMake(rect.origin.x + dx, rect.origin.y + dy, rect.size.width - 2*dx, rect.size.height - 2*dy);
}

@implementation Helper
static NSDateFormatter *dateFormtter;

+ (NSString *)getDateString:(NSDate *)date
{
    if(!dateFormtter){
        dateFormtter = [[NSDateFormatter alloc] init];
        [dateFormtter setDateFormat:@"yyyy-MM-dd"];
    }
    return [dateFormtter stringFromDate:date];
}

+ (NSString *)getCurrentDateString
{
    if(!dateFormtter){
        dateFormtter = [[NSDateFormatter alloc] init];
        [dateFormtter setDateFormat:@"yyyy-MM-dd"];
    }
    return [dateFormtter stringFromDate:[NSDate date]];
}

+ (NSString *)getDateStringForDays:(int)days
{
    if(!dateFormtter){
        dateFormtter = [[NSDateFormatter alloc] init];
        [dateFormtter setDateFormat:@"yyyy-MM-dd"];
    }
    return [dateFormtter stringFromDate:[[NSDate date] dateByAddingTimeInterval:-3600L*24*days]];
}

+ (CGSize)sizeOfText:(NSString *)text font:(UIFont *)font
{
    return [text sizeWithAttributes:@{NSFontAttributeName:font}];
}

+ (CGFloat)textHeightWithWidth:(CGFloat)width font:(UIFont *)font text:(NSString *)text
{
    CGSize constraint = CGSizeMake(width, MAXFLOAT);
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
    CGSize size = [text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading  attributes:dic context:nil].size;
    return ceil(size.height);
}

+ (UIToolbar *)getInputAccessoryViewForCloseKeyboard
{
    return [self getInputAccessoryViewForCloseKeyboardWithTitle:nil];
}

+ (UIToolbar *)getInputAccessoryViewForCloseKeyboardWithTitle:(NSString *)title
{
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 44)];
    toolBar.tintColor = MAINCOLOR;
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *close = [[UIBarButtonItem alloc] initWithTitle:title?:@"收起键盘" style:UIBarButtonItemStylePlain target:self action:@selector(closeKB:)];
    //    close.tintColor = data.mainColor;
    toolBar.items = @[space, close];
    return toolBar;
}

+ (TranlucentToolbar *)getClearInputAccessoryViewForCloseKeyboard
{
    TranlucentToolbar *toolBar = [[TranlucentToolbar alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 44)];
    toolBar.tintColor = MAINCOLOR;
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *close = [[UIBarButtonItem alloc] initWithTitle:@"收起键盘" style:UIBarButtonItemStylePlain target:self action:@selector(closeKB:)];
    //    close.tintColor = data.mainColor;
    toolBar.items = @[space, close];
    return toolBar;
}

+ (void)closeKB:(id)sender
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

+ (UIWindow *)window
{
    AppDelegate *app = [self app];
    return app.window;
}

+ (AppDelegate *)app
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

+(void)showTips:(NSString *)tips forTime:(NSTimeInterval)time inView:(UIView *)view yOffset:(CGFloat)y
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = tips;
    hud.yOffset = y;
    [hud hide:YES afterDelay:time];
}

+(MBProgressHUD *)showWaitHUDTips:(NSString *)tips inView:(UIView *)view yOffset:(CGFloat)y
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.yOffset = y;
    hud.removeFromSuperViewOnHide = YES;
    hud.labelText = tips;
    return hud;
}

+ (UITabBarController *)getTabCon
{
    AppDelegate *app = [self app];
    UIViewController *con = app.window.rootViewController;
    return (UITabBarController *)con;
}

+ (UIViewController *)getCurrentViewController
{
    AppDelegate *app = [self app];
    UIViewController *con = app.window.rootViewController;
    while (YES) {
        if ([con isKindOfClass:UINavigationController.class]) {
            UINavigationController *nav = (UINavigationController *)con;
            con = nav.viewControllers.lastObject;
        }else if ([con isKindOfClass:UITabBarController.class]) {
            UITabBarController *tab = (UITabBarController *)con;
            con = tab.viewControllers[tab.selectedIndex];
        }else if (con.presentedViewController) {
            con = con.presentedViewController;
        }else{
            break;
        }
    }
    
    return con;
}

+ (NSString *)getParamByKey:(NSString *)key inParams:(NSString *)params
{
    NSArray<NSString *> *arr = [params componentsSeparatedByString:@"&"];
    for (NSString *s in arr) {
        NSArray<NSString *> *tmp = [s componentsSeparatedByString:@"="];
        if ([tmp[0] isEqualToString:key]) {
            return [tmp[1] substringWithRange:NSMakeRange(1, tmp[1].length - 2)];
        }
    }
    return nil;
}

+ (void)callToServer:(id)sender
{
    UIApplication *app = [UIApplication sharedApplication];
    NSURL *url = [NSURL URLWithString:@"tel://02088991969"];
    if ([app canOpenURL:url]) {
        [app openURL:url];
    }else{
        SHOW_ALERT(@"您的设备不支持打电话。");
    }
}

+ (void)showLoginControllerIn:(UIViewController *)conParent
{
    LoginViewController *login = [[LoginViewController alloc] initWithStyle:UITableViewStyleGrouped];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
    nav.navigationBar.barTintColor = MAINCOLOR;
    nav.navigationBar.tintColor = WHITE(1);
    nav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:WHITE(1)};
    [conParent presentViewController:nav animated:YES completion:nil];
}

+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+ (NSString *)getRandomString:(int)num
{
    char *data = malloc(num);
    for (int x=0;x<num;data[x++] = (char)('A' + (arc4random_uniform(26))));
    NSString *res = [[NSString alloc]initWithBytes:data length:num encoding:NSUTF8StringEncoding];
    free(data);
    return res;
}

+ (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    // Free memory
    freeifaddrs(interfaces);
    
    return address;
}

+ (NSString *)IntToString:(NSInteger)num
{
    return [NSString stringWithFormat:@"%ld",num];
}

+ (NSString *)floatToString:(CGFloat)num reservCount:(int)count
{
    NSString *format = [NSString stringWithFormat:@"%%.%dlf",count];
    return [NSString stringWithFormat:format,num];
}

+ (BOOL)isPostProcess:(NSString *)name
{
    return [@[@"专色",@"其它",@"压型",@"压折",@"压纹",@"折页",@"烫金",@"粘合",@"装订",@"覆膜",@"过UV"] containsObject:name];
}

@end
